"""
    Controller for quantity addition dictionary table.
"""

from turbogears import expose, widgets, redirect
from mnemoply import model
from mnemoply.controllers.lookup import LookupController, TableCol, SQLObjectLookupDataSource
from mnemoply.controllers.crud import CRUDController
from mnemoply.widgets import DictField, Span, GridField
from mnemoply.utils import LocalMenuItem


class RangeField(DictField):
    """
        Drop-down menu with actual range as content.
    """

    data = dict([(x, x) for x in range(1, 21)])


class QuantityAdditionWidget(widgets.Widget):
    name = "range_widget"
    headers = [_("Amount of students"),
               _("Addition")]
    rows = []

    validator = None

    def __init__(self, _from, _to):
        super(QuantityAdditionWidget, self).__init__(_from, _to)

        self.rows = []
        for n in range(_from, _to + 1):
            self.rows.append(self.getRow(n))

    def getRow(self, num):
        return [
            Span(value=num),
            widgets.TextField(str(num), attrs={'size':5, 'value':'0.00'}),
        ]


class QuantityAdditionController(LookupController, CRUDController):
    model_object = model.QuantityAddition
    lookup_columns = [
        TableCol(name='addition', caption=_('Addition')),
        TableCol(name='numStudents', caption=_('Number of students')),
    ]
    view_fields = ['addition', 'numStudents']
    local_menu = [LocalMenuItem(caption=_('Create additions'), href='show_form')]

    def __init__(self):
        LookupController.__init__(self,
            data_source=SQLObjectLookupDataSource(self.model_object),
            columns=self.lookup_columns,
            title=self.model_object.model_title,
        )
        CRUDController.__init__(self, model_object=self.model_object)

    @expose("genshi:mnemoply.templates.create_quantity_additions")
    def show_form(self):
        form = widgets.TableForm(
            name="additions_paper",
            fields=[
                RangeField(name='from', not_empty=True, label=_("From ")),
                RangeField(name='to', not_empty=True, label=_("To ")),
                ],
            submit_text=_("Add"),
            action='add_additions',
            )
        return dict(form=form)

    @expose("genshi:mnemoply.templates.create_quantity_additions")
    def add_additions(self, **kw):
        form = widgets.TableForm(
            name="AgreementPaper",
            fields=[GridField(QuantityAdditionWidget(_from=int(kw['from']), _to=int(kw['to'])))],
            submit_text=_("Add"),
            action='add_to_db',
            )
        return dict(form=form)

    @expose()
    def add_to_db(self, **kw):
        for k, v in kw['widget'].iteritems():
            try:
                model.QuantityAddition(addition=v, numStudents=int(k))
            except:
                pass

        raise redirect("./")

exposed = QuantityAdditionController()
